import java.util.List;

public class Num2 {
    //给你两个非空 的链表，表示两个非负的整数。它们每位数字都是按照逆序的方式存储的，并且每个节点只能存储一位数字。
    //请你将两个数相加，并以相同形式返回一个表示和的链表。
    public static void main(String[] args) {
        ListNode l1 = new ListNode(9);
        ListNode pre1 = l1;
        for (int i = 0; i < 6; i++) {
            ListNode node = new ListNode(9);
            pre1.next = node;
            pre1 = node;
        }
        System.out.println(l1.toString());

        ListNode l2 = new ListNode(9);
        ListNode pre2 = l2;
        for (int i = 0; i < 3; i++) {
            ListNode node = new ListNode(9);
            pre2.next = node;
            pre2 = node;
        }

        Num2 num2 = new Num2();
        System.out.println(num2.addTwoNumbers(l1, l2).toString());
    }
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int sum = 0;
        int n = 0;
        ListNode dummyHead = new ListNode();
        ListNode pre = dummyHead;
        while (l1 != null && l2 != null) {
            sum = l1.val + l2.val;
            if (n == 1) {
                sum++;
            }
            n = sum >= 10 ? 1 : 0;
            sum = sum >= 10 ? sum - 10 : sum;
            ListNode node = new ListNode(sum);
            pre.next = node;
            pre = pre.next;
            l1 = l1.next;
            l2 = l2.next;
        }
        if (n == 1) sum++;
        if (l1 == null && l2 != null) {
            ListNode node = new ListNode(sum + l2.val);
            pre.next = node;
            pre = pre.next;
            l2 = l2.next;
            while (l2 != null) {
                ListNode node1 = new ListNode(l2.val);
                pre.next = node;
                pre = pre.next;
                l2 = l2.next;
            }
        } else if (l2 == null && l1 != null) {
            ListNode node = new ListNode(sum + l1.val);
            pre.next = node;
            pre = pre.next;
            l1 = l1.next;
            while (l1 != null) {
                ListNode node1 = new ListNode(l1.val);
                pre.next = node;
                pre = pre.next;
                l1 = l1.next;
            }
        }
        return dummyHead.next;
    }
}
